// pages/index/index.js
const app = getApp();
const db = wx.cloud.database();
const _ = db.command;

Page({
    data: {
        chatroomData: [],
        filteredChatroomData: [],
        searchKeyword: ''
    },
    onShow: function () {
      const tabBar = this.getTabBar();
      if (tabBar) {
        const route = this.route;
        tabBar.setSelectedIndexByRoute(route);
      }
    },
    onLoad: function () {
        this.getChatroomData();
        this.checkAndCreateDeepSeekChatroom();
    },

    getChatroomData: function () {
      db.collection('chatrooms')
        .orderBy('createdAt', 'desc') 
        .get()
        .then(res => {
              console.log('获取的聊天室数据:', res.data); 
              const filteredData = res.data.filter(item => item.name!== 'DeepSeek');
              this.setData({
                  chatroomData: filteredData,
                  filteredChatroomData: filteredData
              });
          })
        .catch(err => {
              console.error(err);
          });
  },

    onChange: function (event) {
        this.setData({
            searchKeyword: event.detail
        });
    },

    onSearch: function () {
        const keyword = this.data.searchKeyword.toLowerCase();
        const filteredData = this.data.chatroomData.filter(item => {
            // 过滤掉 name 为 DeepSeek 的数据，并根据关键词进行搜索
            return item.name!== 'DeepSeek' && (
                item.name.toLowerCase().includes(keyword) ||
                (item.description && item.description.toLowerCase().includes(keyword))
            );
        });
        this.setData({
            filteredChatroomData: filteredData
        });
    },

    navigateToDetail: function (event) {
        const roomId = event.currentTarget.dataset.roomId;
        console.log("输出真正的roomId", roomId);
        wx.navigateTo({
            url: `/pages/chat_page/chat_page?roomId=${roomId}`
        });
    },

    navigateToCreateChatroom: function () {
        wx.navigateTo({
            url: '/pages/create_chatroom/create_chatroom'
        });
    },

    // 刷新数据的函数
    refreshData: function () {
        this.getChatroomData();
    },

    // 下拉刷新处理函数
    onPullDownRefresh: function () {
        this.refreshData();
        // 模拟数据加载完成，停止下拉刷新动画
        setTimeout(() => {
            wx.stopPullDownRefresh();
        }, 1000);
    },

    // 检查并创建 DeepSeek 聊天室
    checkAndCreateDeepSeekChatroom: function () {
        const userId = app.globalData.userId;
        if (!userId) {
            console.error('用户 ID 未获取到');
            return;
        }

        // 查询用户信息，获取 deepseekId
        db.collection('users')
           .doc(userId)
           .get()
           .then(res => {
                const user = res.data;
                const deepseekId = user.deepseekId;
                if (!deepseekId) {
                    // deepseekId 为空，创建新的 DeepSeek 聊天室
                    this.createDeepSeekChatroom(userId);
                }
            })
           .catch(err => {
                console.error('查询用户信息失败:', err);
            });
    },

    // 创建 DeepSeek 聊天室
    createDeepSeekChatroom: function (userId) {
        // 创建新的聊天室
        db.collection('chatrooms')
           .add({
                data: {
                    name: 'DeepSeek',
                    description: '智能AI大模型',
                    createdAt: new Date(),
                    updatedAt: new Date(),
                    creatorId: userId,
                    memberCount: 1
                }
            })
           .then(res => {
                const roomId = res._id;
                // 将用户添加为聊天室成员
                return db.collection('chatroomMembers')
                   .add({
                        data: {
                            roomId: roomId,
                            userId: userId,
                            joinedAt: new Date(),
                            role: 'admin'
                        }
                    })
                   .then(() => {
                        // 更新用户的 deepseekId 属性
                        return db.collection('users')
                           .doc(userId)
                           .update({
                                data: {
                                    deepseekId: roomId
                                }
                            });
                    })
                   .then(() => {
                        // 创建初始消息
                        const message = {
                            roomId: roomId,
                            senderId: 'deepSeek',
                            content: '我是蓝心大模型，很高兴见到你！',
                            sendTimeTs: Date.now(),
                            likeCount: 0,
                            collectCount: 0,
                            showTime: true
                        };
                        return db.collection('messages')
                           .add({
                                data: message
                            });
                    })
                   .then(() => {
                        // 将新的 deepseekId 赋值给全局变量
                        app.globalData.deepseekId = roomId;
                        console.log('DeepSeek 聊天室创建成功，初始消息创建成功，全局变量 deepseekId 已更新');
                    });
            })
           .then(() => {
                console.log('DeepSeek 聊天室创建成功，初始消息创建成功');
            })
           .catch(err => {
                console.error('创建 DeepSeek 聊天室或初始消息失败:', err);
            });
    }
});